package tw.com.servlet;
import java.io.File;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.jfree.chart.servlet.ServletUtilities;

/**
 * Servlet implementation class excelExport
 */
public class ExportExcel extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ExportExcel() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * Init method.
     *
     * @throws ServletException never.
     */
    public void init() throws ServletException {
        return;
    }
    
    /**
     * Service method.
     *
     * @param request  the request.
     * @param response  the response.
     *
     * @throws ServletException ??.
     * @throws IOException ??.
     */
    public void service(HttpServletRequest request,
                        HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("ExportExcelStart");
        String filename = request.getParameter("filename");

        if (filename == null) {
            throw new ServletException("Parameter 'filename' must be supplied");
        }

        //  Replace ".." with ""
        //  This is to prevent access to the rest of the file system
        filename = ServletUtilities.searchReplace(filename, "..", "");

        //  Check the file exists
        File file = new File(System.getProperty("java.io.tmpdir"), filename);
        if (!file.exists()) {
            throw new ServletException("File '" + file.getAbsolutePath()
                    + "' does not exist");
        }

        String mimeType = null;
        if (filename.length() > 5) {
            if (filename.substring(filename.length() - 5,
                    filename.length()).equals(".xls")) {
                mimeType = "application/excel";
            }
        }
        
        if (file.exists()) {
            BufferedInputStream bis = new BufferedInputStream(
                    new FileInputStream(file));

            //  Set HTTP headers
            if (mimeType != null) {
                response.setHeader("Content-Type", mimeType);
            }
            response.setHeader("Content-Length", String.valueOf(file.length()));
            response.setHeader("Content-Disposition","attachment; filename=" + filename);
            SimpleDateFormat sdf = new SimpleDateFormat(
                    "EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
            sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
            response.setHeader("Last-Modified",
                    sdf.format(new Date(file.lastModified())));
            
            BufferedOutputStream bos = new BufferedOutputStream(
                    response.getOutputStream());
            
            byte[] input = new byte[1024];
            boolean eof = false;
            while (!eof) {
                int length = bis.read(input);
                if (length == -1) {
                    eof = true;
                }
                else {
                    bos.write(input, 0, length);
                }
            }
            bos.flush();
            bis.close();
            bos.close();
        }
        else {
            throw new FileNotFoundException(file.getAbsolutePath());
        }
  
        file.delete();

        return;
    }
}
